package com.wkbb.basic.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


/**
 * @author dengjingyuan
 * @date 2019-07-04 10:32
 */
@Slf4j
public class YouTuUtil {
	protected static int connectTimeout = 10000; // ms
	protected static int readTimeout = 30000; // ms

	public static final String ADDPERSON = "/api/v1/face/add_person";

	public static final String DELETEPERSON = "/api/v1/face/del_person";

	public static final String ADDFACE = "/api/v1/face/add_face";

	public static final String DELETEFACE = "/api/v1/face/del_face";

	public static final String PULLPERSONS = "/api/v1/face/pull_persons";

	public static final String PULLFACES = "/api/v1/face/pull_faces";

	public static final String FACEIDENTIFY = "/api/v1/face/identify";

	public static final String FACEDETECT = "/api/v1/face/face_detect";

	public static final String FACECOMPARE = "/api/v1/face/face_compare";

	public static final String ERRORMSG="errormsg";

	public static final Integer ERRORCODETYPE=0;

	public static final String CODE="code";


	/**
	 * 请求成功
	 */
	public static final String CODE_SUCCESS = "0";

	public static final String FACESUCCESS="ok";

	public static final String ERRORCODE="ok";

	public static final Byte SOURCETYPE=new Byte("1");

	public static final String ALREADYEXISTS="1204";

	public static final Integer ERRORCODETYPE1305=1305;

	public static final Integer FACENOTCOMPLETE=1392;

	public static final Integer PERSONIDNOTEXIST=1202;

	public static final Integer ERRORCODETYPE110110=110110;

	public static final Integer ERRORCODETYPE110114=110114;

	public static final Integer ERRORCODETYPE110106=110106;

	public static final Integer ERRORCODETYPE110107=110107;

	public static final Integer ERRORCODETYPE110108=110108;

	public static final Integer ERRORCODETYPE110109=110109;

	public static final Integer ERRORCODETYPE110111=110111;

	public static final Integer ERRORCODETYPE110112=110112;

	public static final Integer ERRORCODETYPE110113=110113;

	public static final Integer ERRORCODETYPE110115=110115;

	public static final Integer ERRORCODETYPE110116=110116;

	public static final String COSLINKPRO = "pro-1251785967";

	public static final String COSLINKSMART = "p.qpic.cn";

	public static final String COSLINKWX = "picshcos.wkbaob";

	public static final String COSLINKWXTEST = "picshcostest.wkbaob";

	private static class TrustAnyTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	/**
	 * post方式请求服务器(https协议)
	 *
	 * @param url
	 *            请求地址
	 * @param content
	 *            参数
	 * @param charset
	 *            编码
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @throws IOException
	 */
	public static String post(String url, String content,String charset,String sign,String txToken)
			throws NoSuchAlgorithmException, KeyManagementException,
			IOException {
		long startTime = System.currentTimeMillis();

		URL console = new URL(url);
		Integer length = content.length();
		HttpURLConnection conn = (HttpURLConnection) console.openConnection();
		//文档要求填写的Header参数
		conn.setRequestProperty("Cookie", txToken);
		conn.setRequestProperty("Content-Length",length.toString());
		conn.setRequestProperty("Content-Type","text/json");
		conn.setRequestProperty("Authorization", sign);
		//补充超时时间
		conn.setConnectTimeout(connectTimeout);
		conn.setReadTimeout(readTimeout);
		//文档要求填写的Header参数
		conn.setDoOutput(true);
		conn.connect();
		long connectTime = System.currentTimeMillis();

		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(content.getBytes(charset));
		// 刷新、关闭
		out.flush();
		out.close();

		BufferedReader in = null;
		in = new BufferedReader(
				new InputStreamReader(conn.getInputStream(), charset));
		long inputTime = System.currentTimeMillis();

		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		long endTime = System.currentTimeMillis();
		log.info("优图POST请求url：{}，处理过程时长分析，【建立连接】：{},【发送请求】：{},【处理结束】：{},【返回值】:{}",url,connectTime-startTime,inputTime-startTime,endTime-startTime,JSONObject.parseObject(result));
//		System.err.println("result:" + result);
		return result;
	}

	public static  ResultDTO<Object> checkYouTuResult(String result, ServiceConfig serviceConfig){

		if (JSON.isValid(result)) {
			if (YouTuUtil.FACENOTCOMPLETE.equals(JSONObject.parseObject(result).get("errorcode"))) {

				return new ResultDTO<>(ErrorCode.FACENOTCOMPLETE);
			} else if (YouTuUtil.PERSONIDNOTEXIST.equals(JSONObject.parseObject(result).get("errorcode"))) {

				return new ResultDTO<>(ErrorCode.PERSONIDNOTEXIST);
			} else if (YouTuUtil.ERRORCODETYPE.equals(JSONObject.parseObject(result).get("errorcode"))) {

				if (null != JSONObject.parseObject(result).get("result") && serviceConfig.getFaceCompare().compareTo(new BigDecimal(JSONObject.parseObject(result).get("result").toString())) == 1) {
					return new ResultDTO<>(ErrorCode.ACCURACYCOMPARE);
				}

				if (null != JSONObject.parseObject(result).get("face_num") && Integer.parseInt(JSONObject.parseObject(result).get("face_num").toString()) == 0) {
					return new ResultDTO<>(ErrorCode.CHECKFACEERROR);
				}

				//如果优图返回成功并且ret_codes数组里面有值,返回对应错误码
				if (null != JSONObject.parseObject(result).get("ret_codes") && JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).size() > 0) {

					if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110106)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120007);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110107)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120008);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110108)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120009);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110109)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120010);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110110)) {
						return new ResultDTO<>(ErrorCode.CHECKFACEERROR);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110111)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120011);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110112)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120012);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110113)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120013);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110114)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120014);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110115)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120015);

					} else if (JSONObject.parseArray(JSONObject.parseObject(result).get("ret_codes").toString()).get(0).equals(YouTuUtil.ERRORCODETYPE110116)) {
						return new ResultDTO<>(ErrorCode.CHECKFACE2120016);
					}
				}
			} else if (YouTuUtil.ERRORCODETYPE110110.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACEERROR);

			} else if (YouTuUtil.ERRORCODETYPE110114.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.FACETYPEERROR);

			} else if (YouTuUtil.ERRORCODETYPE110106.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120007);

			} else if (YouTuUtil.ERRORCODETYPE110107.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120008);

			} else if (YouTuUtil.ERRORCODETYPE110108.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120009);

			} else if (YouTuUtil.ERRORCODETYPE110109.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120010);

			} else if (YouTuUtil.ERRORCODETYPE110111.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120011);

			} else if (YouTuUtil.ERRORCODETYPE110112.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120012);

			} else if (YouTuUtil.ERRORCODETYPE110113.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120013);

			} else if (YouTuUtil.ERRORCODETYPE110115.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120015);

			} else if (YouTuUtil.ERRORCODETYPE110116.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120016);

			} else if (YouTuUtil.ERRORCODETYPE1305.equals(JSONObject.parseObject(result).get("errorcode"))) {
				return new ResultDTO<>(ErrorCode.CHECKFACE2120017);
			}

		} else {
			return new ResultDTO<>(ErrorCode.ADDORMODIFYFACEERROR);
		}
		return new ResultDTO<>(result);
	}
}
